package fmppc.config;

import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
import com.baomidou.mybatisplus.extension.MybatisMapWrapperFactory;
import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.pagination.optimize.JsqlParserCountOptimize;
import fmppc.config.properties.MyBatisPlusPropertiesConfigBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * 类描述:  MybatisPlus配置
 *
 * @author 王雷
 * @version 1.0.0
 * @date 2020/4/10 0010 上午 10:54
 */
@Configuration
@AutoConfigureAfter(SqlSessionFactory.class)
@EnableTransactionManagement(proxyTargetClass = true)
@EnableConfigurationProperties(value = MyBatisPlusPropertiesConfigBean.class)
public class MyBatisConfig {

    private final MyBatisPlusPropertiesConfigBean myBatisPlusPropertiesConfigBean;

    public MyBatisConfig(MyBatisPlusPropertiesConfigBean myBatisPlusPropertiesConfigBean) {
        this.myBatisPlusPropertiesConfigBean = myBatisPlusPropertiesConfigBean;
    }

    /**
     * 分页插件，自动识别数据库类型
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        // 设置请求的页面大于最大页后操作， true调回到首页，false 继续请求  默认false
        paginationInterceptor.setOverflow(myBatisPlusPropertiesConfigBean.getOverIsToPage());
        //设置最大单页限制数量，默认 500 条，-1 不受限制
        paginationInterceptor.setLimit(myBatisPlusPropertiesConfigBean.getLimtMaxSize());
        // 开启 count 的 join 优化,只针对部分 left join
        paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(myBatisPlusPropertiesConfigBean.getCountJoinOptimize()));
        return paginationInterceptor;
    }

    /**
     * 乐观锁插件
     */
    @Bean
    public OptimisticLockerInterceptor optimisticLockerInterceptor() {
        return new OptimisticLockerInterceptor();
    }


    /**
     * 功能描述：驼峰命名规范处理
     * @date : 2022/12/8 0008 下午 9:49
     */
    @Bean
    public ConfigurationCustomizer mybatisConfigurationCustomizer(){
        return configuration -> configuration.setObjectWrapperFactory(new MybatisMapWrapperFactory());
    }
}
